package com.project2.controller;

import com.project2.anno.SaveLog;
import com.project2.bean.ResultVo;
import com.project2.bean.bo.AdminLoginBo;
import com.project2.bean.po.MarketAdmin;
import com.project2.bean.po.MarketUser;
import com.project2.bean.vo.AuthLoginInfo;
import com.project2.bean.vo.AuthLoginVo;
import com.project2.shiro.MarketToken;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.io.Serializable;

/**
 * TODO
 *
 * @param
 * @author wj
 * @return
 */
@RestController
@RequestMapping("wx/auth")
public class WxAuthController {
    @SaveLog(value = "小程序用户登录")
    @RequestMapping("login")
    public ResultVo login(@RequestBody AdminLoginBo adminLoginBo, HttpSession session){
        //获取认证信息
        String password = adminLoginBo.getPassword();
        String username = adminLoginBo.getUsername();
        //获得subject对象执行认证
        Subject subject = SecurityUtils.getSubject();
        //UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);
        MarketToken admin = new MarketToken(username, password, "wx");
        try{
            subject.login(admin);
        }catch (Exception e){
            e.printStackTrace();
        }

        //判断是否认证成功
        boolean authenticated = subject.isAuthenticated();

        // cbj 0815修改
        if(authenticated) {
            MarketUser marketUser = (MarketUser) subject.getPrincipals().getPrimaryPrincipal();

            Serializable id = subject.getSession().getId();

            AuthLoginVo authLoginVo = new AuthLoginVo();
            AuthLoginInfo authLoginInfo = new AuthLoginInfo();
            authLoginInfo.setAvatar(marketUser.getAvatar());
            authLoginInfo.setNickName(marketUser.getNickname());
            authLoginVo.setToken(((String) id));

            session.setAttribute(authLoginVo.getToken(), marketUser);


            return ResultVo.ok(authLoginVo);
        }
        ResultVo resultVo = new ResultVo();
        resultVo.setErrno(401);
        resultVo.setErrmsg("登录失败，请重试");
        return  resultVo;
    }

    @SaveLog(value = "小程序用户退出")
    @RequestMapping("logout")
    public ResultVo logout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return ResultVo.ok();
    }


}
